package spring.cloud.tasks.executor.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.executor.task.TaskExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Setter
@Getter
public class TaskIdToTaskExecutorMap {
    //添加任务执行器的时候，先将taskId添加到taskIdSet，避免重复添加。
    //删除任务执行器先进行删除任务执行器。避免先从taskIdSet移除了，但真正关闭执行器异常了那就永远关闭不了任务执行器了就悲剧了。
    public List<String> taskIdSet = new ArrayList<>();
    private ConcurrentHashMap<String, TaskExecutor> taskIdToTaskExecutorMap = new ConcurrentHashMap<>();

    public void addTaskExecutor(final String taskId, final TaskExecutor taskExecutor) {
        taskIdToTaskExecutorMap.put(taskId, taskExecutor);
    }

    public TaskExecutor removeTaskExecutor(String taskId) {
        return taskIdToTaskExecutorMap.remove(taskId);
    }

    public ConcurrentHashMap<String, TaskExecutor> getTaskIdToTaskExecutorMap() {
        return taskIdToTaskExecutorMap;
    }

    public TaskExecutor getTaskExecutor(String taskId) {
        return taskIdToTaskExecutorMap.get(taskId);
    }

    public ConcurrentHashMap<String, TaskExecutor> removeAndGetTaskIdToTaskExecutorMap() {
        ConcurrentHashMap<String, TaskExecutor> taskIdToTaskExecutorMap = new ConcurrentHashMap<>();
        taskIdToTaskExecutorMap.putAll(taskIdToTaskExecutorMap);
        this.taskIdToTaskExecutorMap.clear();
        return taskIdToTaskExecutorMap;
    }


}
